package com.wl.jetpackdemo.chat.emoji

import android.content.Context
import java.io.InputStream
import java.util.regex.Pattern
import javax.xml.parsers.SAXParser
import javax.xml.parsers.SAXParserFactory

/**
 *
 * Created by wangliang on 2021/2/20.
 */
object EmojiUtils {

    var mEmotionsMap: HashMap<String, Emoticon>? = null
    var mEmotionsList: List<Emoticon>? = null
    private var mPattern: Pattern? = null

    fun getAllEmojiData(): List<Emoticon>? {
        return mEmotionsList
    }

    public fun parseConfigFile(context: Context) {
        try {
            // SAX解析的工厂对象
            val factory: SAXParserFactory = SAXParserFactory.newInstance()
            // 得到sax的解析器
            val saxParser: SAXParser = factory.newSAXParser()
            // 创建handler对象
            val handlerService = XmlEmojiHandler()
            val `is`: InputStream = context.assets.open("emoticon/emoji.xml")
            // 直接解析
            saxParser.parse(`is`, handlerService)
            // 通过handlerService对象获取
            mEmotionsList = handlerService.getList()
            val patternString: StringBuilder = StringBuilder(
                    mEmotionsList!!.size * 3)

            patternString.append('(')
            mEmotionsMap = HashMap<String, Emoticon>()
            for (i in 0 until mEmotionsList!!.size) {
                val emo: Emoticon = mEmotionsList!!.get(i)
                patternString.append(Pattern.quote(emo.tag))
                patternString.append('|')
                emo.tag?.let { mEmotionsMap!!.put(it, emo) }
            }
            patternString.replace(patternString.length - 1,
                    patternString.length, ")")
            mPattern = Pattern.compile(patternString.toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}